﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using MockupDesigner.AppItems.Documents;

namespace MockupDesigner.AppItems.Commands
{
    public class SaveCommand : ICommand
    {
        public CommandType CommandType
        {
            get { return CommandType.NonDisturbing; }
        }

        public bool isSaveAs { get; set; }

        private Document document;

        public void Execute(object target, params object[] parameters)
        {
            if (!(target is Window1))
            {
                throw new InvalidCastException("The target must be the Window");
            }
            if (parameters.Length == 0 || !(parameters[0] is Document))
            {
                throw new InvalidCastException("The parameter must be a Document");
            }

            this.document = (Document)parameters[0];

            IEnumerable<DesignerItem> designerItems = this.document.DesignerCanvas.Children.OfType<DesignerItem>();
            XElement designerItemsXML = DocumentSerializationService.SerializeDesignerItems(designerItems);

            XElement root = new XElement("Root");
            root.Add(designerItemsXML);

            if (isSaveAs)
                this.document.DesignerCanvas.SerializationService.SaveDocumentAs(root, document);
            else
                this.document.DesignerCanvas.SerializationService.SaveDocument(root, document);
        }


        public void Redo()
        {
            // Nothing to do
        }

        public void Undo()
        {
            // Nothing to do
        }

    }
}
